<template>
  <div class="certificates-page">
    <!-- 添加粒子背景 -->
    <div class="particles-container">
      <div v-for="n in 20" :key="n" class="particle" :style="{ 
        '--delay': `${Math.random() * 5}s`,
        '--duration': `${Math.random() * 10 + 10}s`,
        '--position': `${Math.random() * 100}%`,
        '--size': `${Math.random() * 30 + 10}px`
      }"></div>
    </div>
    
    <div class="page-title-section">
      <div class="magical-underline"></div>
      <h1 class="magical-title">证书管理系统</h1>
      <div class="title-decoration left"></div>
      <div class="title-decoration right"></div>
    </div>

    <!-- 只保留这个标签组件 -->
    <div class="certificate-tabs-container">
      <div class="certificate-tabs">
        <div 
          class="tab" 
          :class="{ active: activeTab === 'browse' }"
          @click="setActiveTab('browse')"
        >
          <i class="el-icon-document"></i>
          <span>浏览证书</span>
            </div>
        <div 
          class="tab" 
          :class="{ active: activeTab === 'verify' }"
          @click="setActiveTab('verify')"
        >
          <i class="el-icon-search"></i>
          <span>查询证书</span>
          </div>
      </div>
      <div class="tab-actions">
        <el-button type="default" class="action-button" @click="handleRevokeDialog">
          <i class="el-icon-delete"></i> 撤销证书
            </el-button>
        <el-button type="primary" class="action-button" @click="dialogVisible = true">
              <i class="el-icon-plus"></i> 颁发证书
            </el-button>
          </div>
        </div>

    <!-- 添加证书流程指引 -->
    <div class="cert-process-guide">
      <div class="process-connector"></div>
      <div class="process-step">
        <div class="step-number">1</div>
        <div class="step-title">选择学生</div>
        <div class="step-desc">从学生列表中选择需要颁发证书的学生</div>
      </div>
      <div class="process-step">
        <div class="step-number">2</div>
        <div class="step-title">填写信息</div>
        <div class="step-desc">完善证书类型、编号等相关信息</div>
      </div>
      <div class="process-step">
        <div class="step-number">3</div>
        <div class="step-title">上链确认</div>
        <div class="step-desc">生成区块链交易，确保证书不可篡改</div>
      </div>
      <div class="process-step">
        <div class="step-number">4</div>
        <div class="step-title">证书生效</div>
        <div class="step-desc">交易确认后，证书正式生效并可验证</div>
      </div>
    </div>

    <!-- 添加搜索和过滤功能 -->
    <div class="search-filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索证书编号或类型"
        prefix-icon="el-icon-search"
        clearable
        class="search-input"
        @input="handleSearch"
      />
      <el-switch
        v-model="filterInvalidDates"
        active-text="过滤无效日期"
        inactive-text="显示所有数据"
        @change="handleFilterChange"
        style="margin-left: 20px;"
        active-color="#6149cd"
      />
    </div>

    <el-card class="main-card">
      <!-- 添加光晕效果 -->
      <div class="glow-effect"></div>
      
      <div class="table-container">
        <el-table 
          v-loading="loading" 
          :data="filteredCertificates" 
          style="width: 100%"
          border
          stripe
          class="certificate-table"
          :header-cell-style="{ 
            background: '#f0f7ff', 
            color: '#4a5568',
            textAlign: 'center',
            fontWeight: '600',
            padding: '12px 0',
            fontSize: '15px'
          }"
          :cell-style="{ 
            textAlign: 'center',
            padding: '12px 0'
          }"
        >
          <el-table-column prop="certificateId" label="证书ID" width="100" />
          <el-table-column label="学生ID" width="300">
            <template #default="scope">
              <el-tooltip :content="'完整地址: ' + scope.row.studentId" placement="top" effect="light">
                <div class="student-id-cell">
                  <code class="id-code">{{ scope.row.studentId }}</code>
                  <el-button v-if="scope.row.studentId" type="text" size="small" @click="copyToClipboard(scope.row.studentId)">
                    复制
                  </el-button>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="证书类型" width="150">
            <template #default="scope">
              {{ removeQuotes(scope.row.certificateType) }}
            </template>
          </el-table-column>
          <el-table-column label="证书编号" width="180">
            <template #default="scope">
              {{ removeQuotes(scope.row.certificateNumber) }}
            </template>
          </el-table-column>
          <el-table-column label="颁发日期" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column label="颁发机构" width="180">
            <template #default="scope">
              {{ removeQuotes(scope.row.institution) }}
            </template>
          </el-table-column>
          <el-table-column prop="isValid" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isValid ? 'success' : 'danger'">
                {{ scope.row.isValid ? '有效' : '已撤销' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="区块链信息" width="120">
            <template #default="scope">
              <el-popover
                placement="top"
                :width="400"
                trigger="hover"
              >
                <template #default>
                  <div>
                    <p><strong>交易哈希:</strong> {{ scope.row.txHash || '未知' }}</p>
                    <p><strong>区块号:</strong> {{ scope.row.blockNumber || '未知' }}</p>
                    <p v-if="scope.row.blockHash"><strong>区块哈希:</strong> {{ scope.row.blockHash }}</p>
                    <p v-if="scope.row.gasUsed"><strong>Gas使用量:</strong> {{ scope.row.gasUsed }}</p>
                    <p><strong>证书哈希:</strong> {{ scope.row.certificateHash || scope.row.hash || '未知' }}</p>
                    <p><strong>状态:</strong> {{ scope.row.status || '已确认' }}</p>
                  </div>
                </template>
                <template #reference>
                  <el-button type="info" size="small">区块信息</el-button>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  type="info"
                  size="small"
                  @click="viewCertificateDetails(scope.row)"
                >
                  详情
                </el-button>
                <el-button
                  v-if="scope.row.isValid"
                  type="danger"
                  size="small"
                  @click="handleRevoke(scope.row.certificateId)"
                >
                  撤销
                </el-button>
                <el-button
                  v-if="scope.row.isValid"
                  type="primary"
                  size="small"
                  @click="openUpdateDialog(scope.row)"
                >
                  更新
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <div v-if="isDataEmpty" class="empty-text">
      <div class="magical-circle"></div>
      <i class="el-icon-warning-outline floating-icon"></i>
      <span>暂无证书数据</span>
    </div>

    <el-dialog v-model="dialogVisible" title="颁发证书" width="550px" custom-class="fancy-dialog" destroy-on-close>
      <div class="dialog-background"></div>
      <div class="dialog-content">
        <div class="form-header">
          <div class="certificate-icon-container">
            <i class="el-icon-plus floating-dialog-icon"></i>
          </div>
          <h3 class="form-title">颁发新证书</h3>
          <div class="floating-dots">
            <span></span><span></span><span></span>
          </div>
        </div>
        
        <el-form :model="form" label-width="120px" class="styled-form" label-position="top" status-icon>
          <el-form-item label="学生姓名">
            <el-select 
              v-model="form.studentId" 
              placeholder="请选择学生" 
              filterable
              class="styled-select"
            >
              <template #prefix>
                <i class="el-icon-user form-icon"></i>
              </template>
              <el-option
                v-for="student in students"
                :key="student.studentId"
                :label="student.name"
                :value="student.studentId"
              >
                <div class="option-content">
                  <i class="el-icon-user"></i>
                  <span>{{ student.name }}</span>
                  <small class="option-description">{{ student.education }} · {{ student.graduationYear }}</small>
                </div>
              </el-option>
            </el-select>
            <div class="form-tip">选择要颁发证书的学生</div>
          </el-form-item>
          
          <el-form-item label="证书类型">
            <el-select 
              v-model="form.certificateType" 
              placeholder="请选择证书类型"
              class="styled-select"
            >
              <template #prefix>
                <i class="el-icon-collection-tag form-icon"></i>
              </template>
              <el-option label="学位证书" value="学位证书">
                <div class="option-content">
                  <i class="el-icon-medal-1" style="color: #409EFF;"></i>
                  <span>学位证书</span>
                </div>
              </el-option>
              <el-option label="毕业证书" value="毕业证书">
                <div class="option-content">
                  <i class="el-icon-collection" style="color: #67C23A;"></i>
                  <span>毕业证书</span>
                </div>
              </el-option>
              <el-option label="荣誉证书" value="荣誉证书">
                <div class="option-content">
                  <i class="el-icon-trophy" style="color: #E6A23C;"></i>
                  <span>荣誉证书</span>
                </div>
              </el-option>
            </el-select>
            <div class="form-tip">选择要颁发的证书类型</div>
          </el-form-item>
          
          <el-form-item label="证书编号">
            <el-input 
              v-model="form.certificateNumber" 
              placeholder="请输入证书编号" 
              prefix-icon="el-icon-document"
              class="styled-input"
            >
              <template #suffix>
                <div v-if="form.certificateNumber" class="magic-effect-container">
                  <div class="magic-sparkle"></div>
                </div>
              </template>
            </el-input>
            <div class="form-tip">证书的唯一编号，如学校发放的证书编号</div>
          </el-form-item>
          
          <el-form-item label="颁发日期">
            <div class="date-picker-wrapper">
              <el-date-picker
                v-model="form.issueDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="styled-date-picker"
              />
            </div>
            <div class="form-tip">证书颁发的日期</div>
          </el-form-item>
          
          <el-form-item label="颁发机构">
            <el-input 
              v-model="form.institution" 
              placeholder="请输入颁发机构" 
              prefix-icon="el-icon-school"
              class="styled-input"
            >
              <template #suffix>
                <div v-if="form.institution" class="magic-effect-container">
                  <div class="magic-sparkle"></div>
                </div>
              </template>
            </el-input>
            <div class="form-tip">颁发证书的机构名称</div>
          </el-form-item>
          
          <div class="form-notice">
            <i class="el-icon-info-filled notice-icon"></i>
            <span>证书信息将被存储在区块链上，请确保信息准确无误</span>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn magical-btn">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting" class="submit-btn magical-btn">
            <div class="btn-bg-effect"></div>
            <i class="el-icon-check"></i> {{ submitting ? '处理中...' : '确认颁发' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="updateDialogVisible" title="更新证书" width="550px" custom-class="fancy-dialog" destroy-on-close>
      <div class="dialog-background"></div>
      <div class="dialog-content">
        <div class="form-header">
          <div class="certificate-icon-container update-icon">
            <i class="el-icon-edit floating-dialog-icon"></i>
          </div>
          <h3 class="form-title">更新证书信息</h3>
          <div class="floating-dots">
            <span></span><span></span><span></span>
          </div>
        </div>
        
        <el-form :model="updateForm" label-width="120px" class="styled-form" label-position="top" status-icon>
          <el-form-item label="证书类型">
            <el-select 
              v-model="updateForm.certificateType" 
              placeholder="请选择证书类型"
              class="styled-select"
            >
              <template #prefix>
                <i class="el-icon-collection-tag form-icon"></i>
              </template>
              <el-option label="学位证书" value="学位证书">
                <div class="option-content">
                  <i class="el-icon-medal-1" style="color: #409EFF;"></i>
                  <span>学位证书</span>
                </div>
              </el-option>
              <el-option label="毕业证书" value="毕业证书">
                <div class="option-content">
                  <i class="el-icon-collection" style="color: #67C23A;"></i>
                  <span>毕业证书</span>
                </div>
              </el-option>
              <el-option label="荣誉证书" value="荣誉证书">
                <div class="option-content">
                  <i class="el-icon-trophy" style="color: #E6A23C;"></i>
                  <span>荣誉证书</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="证书编号">
            <el-input 
              v-model="updateForm.certificateNumber" 
              placeholder="请输入证书编号"
              prefix-icon="el-icon-document"
              class="styled-input"
            >
              <template #suffix>
                <div v-if="updateForm.certificateNumber" class="magic-effect-container">
                  <div class="magic-sparkle"></div>
                </div>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="颁发日期">
            <div class="date-picker-wrapper">
              <el-date-picker
                v-model="updateForm.issueDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="styled-date-picker"
              />
            </div>
          </el-form-item>
          
          <el-form-item label="颁发机构">
            <el-input 
              v-model="updateForm.institution" 
              placeholder="请输入颁发机构"
              prefix-icon="el-icon-school"
              class="styled-input"
            >
              <template #suffix>
                <div v-if="updateForm.institution" class="magic-effect-container">
                  <div class="magic-sparkle"></div>
                </div>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="证书状态">
            <div class="switch-container">
              <el-switch
                v-model="updateForm.isValid"
                active-text="有效"
                inactive-text="无效"
                active-color="#67c23a"
                inactive-color="#f56c6c"
                class="styled-switch"
              />
              <div class="switch-status" :class="{'valid': updateForm.isValid, 'invalid': !updateForm.isValid}">
                {{ updateForm.isValid ? '此证书当前有效' : '此证书当前已撤销' }}
              </div>
            </div>
          </el-form-item>
          
          <div class="form-notice warning" v-if="!updateForm.isValid">
            <i class="el-icon-warning-filled notice-icon"></i>
            <span>将证书状态设为无效相当于撤销证书，此操作一旦提交到区块链将无法撤销</span>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false" class="cancel-btn">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="primary" @click="handleUpdate" class="submit-btn magical-btn">
            <div class="btn-bg-effect"></div>
            <i class="el-icon-check"></i> 确认更新
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import LogService from '@/store/logService'

export default {
  name: 'CertificateManagement',
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    const dialogVisible = ref(false)
    const refreshing = ref(false)
    const updateDialogVisible = ref(false)
    const submitting = ref(false)
    const loading = ref(false) // 添加loading状态变量
    
    // 获取URL查询参数中的学生ID
    const studentIdFilter = computed(() => route.query.studentId)
    
    const form = ref({
      studentId: '',
      certificateType: '',
      certificateNumber: '',
      issueDate: '',
      institution: ''
    })

    const updateForm = ref({
      certificateId: '',
      studentId: '',
      certificateType: '',
      certificateNumber: '',
      issueDate: '',
      institution: '',
      isValid: true
    })

    const formatDate = (timestamp) => {
      if (!timestamp) return '未知日期'
      
      // 检查timestamp是否为秒级时间戳（10位数字），如果是则转为毫秒
      let date;
      if (typeof timestamp === 'number' || !isNaN(Number(timestamp))) {
        // 如果是数字，判断是秒还是毫秒时间戳
        const numberTimestamp = Number(timestamp);
        if (String(numberTimestamp).length <= 10) {
          // 秒转毫秒
          date = new Date(numberTimestamp * 1000);
        } else {
          date = new Date(numberTimestamp);
        }
      } else {
        // 如果是字符串日期等格式
        date = new Date(timestamp);
      }
      
      // 只返回年-月-日格式，不包含时间
      const dateFormat = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      
      // 检测无效日期
      if (dateFormat.includes('NaN')) {
        return '未知日期';
      }
      
      return dateFormat;
    }

    // 新增：去除字符串中的引号
    const removeQuotes = (text) => {
      if (!text) return '';
      
      // 将字符串中的所有引号（单引号和双引号）去除
      return String(text).replace(/['"]/g, '');
    }

    // 添加搜索和过滤功能
    const searchQuery = ref('')
    const filterInvalidDates = ref(true) // 默认开启过滤
    
    const handleSearch = () => {
      console.log('执行搜索:', searchQuery.value);
      // 搜索功能通过computed属性自动实现
    }
    
    const handleFilterChange = (value) => {
      console.log('过滤设置变更:', value);
      LogService.logSystemOperation(value ? '开启证书无效日期过滤' : '关闭证书无效日期过滤', {
        filterStatus: value ? '开启' : '关闭'
      });
    }

    // 过滤后的证书列表
    const filteredCertificates = computed(() => {
      console.log('筛选证书数据, 学生ID过滤器:', studentIdFilter.value)
      
      // 先获取所有证书
      let certificates = store.state.certificates;
      
      // 过滤无效日期的证书
      if (filterInvalidDates.value) {
        certificates = certificates.filter(cert => {
          // 检查日期是否有效
          const dateStr = formatDate(cert.timestamp);
          
          // 检测无效日期模式
          const isInvalidDate = 
            dateStr === 'NaN-NaN-NaN' || 
            dateStr === 'NaN:NaN:NaN' || 
            dateStr.includes('NaN') || 
            dateStr === '未知日期' ||
            dateStr === 'Invalid Date' ||
            !dateStr;
            
          return !isInvalidDate;
        });
      }
      
      // 根据搜索关键词过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase().trim();
        certificates = certificates.filter(cert => {
          const certType = String(cert.certificateType || '').toLowerCase();
          const certNumber = String(cert.certificateNumber || '').toLowerCase();
          const institution = String(cert.institution || '').toLowerCase();
          return certType.includes(query) || 
                 certNumber.includes(query) || 
                 institution.includes(query);
        });
      }
      
      // 根据学生ID过滤
      if (studentIdFilter.value) {
        console.log('按学生ID过滤')
      
      // 根据学生ID筛选证书 - 使用精确匹配
        const filtered = certificates.filter(cert => {
        // 打印证书的学生ID信息，方便调试
        console.log(`证书ID ${cert.certificateId} 的学生信息:`, {
          原始学生ID: cert.studentId,
          过滤器值: studentIdFilter.value
        });
        
        // 1. 精确匹配
        const matchesId = cert.studentId === studentIdFilter.value;
        
        // 2. 部分匹配
        const idStr = String(cert.studentId || '');
        const filterStr = String(studentIdFilter.value || '');
        const partialMatchId = idStr.includes(filterStr) || filterStr.includes(idStr);
        
        return matchesId || partialMatchId;
      })
      
      console.log(`筛选结果: 学生ID ${studentIdFilter.value} 的证书共 ${filtered.length} 条`);
      
        // 如果没有找到匹配的证书，尝试显示所有过滤后的证书
      if (filtered.length === 0) {
          console.log('未找到匹配的证书，显示所有过滤后的证书');
        ElMessage.warning('未找到指定学生的证书记录，显示所有证书');
          return certificates;
      }
      
      return filtered;
      }
      
      return certificates;
    });

    // 修正空数据提示的判断条件
    const isDataEmpty = computed(() => {
      return filteredCertificates.value.length === 0 && !loading.value;
    });

    const submitForm = async () => {
      try {
        submitting.value = true;
        
        const result = await store.dispatch('issueCertificate', {
          studentId: form.value.studentId,
          certificateType: form.value.certificateType,
          certificateNumber: form.value.certificateNumber,
          institution: form.value.institution,
          issueDate: form.value.issueDate
        });
        
        console.log('证书创建成功:', result);
        
        // 记录操作日志
        LogService.logCertificateOperation(`颁发${form.value.certificateType}证书`, {
          studentId: form.value.studentId,
          certificateNumber: form.value.certificateNumber,
          institution: form.value.institution
        });
        
        ElMessage.success('证书已成功创建并上链，请等待区块确认');
        dialogVisible.value = false;
        resetForm();
        
        // 刷新证书列表
        await fetchCertificates();
      } catch (error) {
        console.error('提交表单失败:', error);
        
        // 记录失败日志
        LogService.logCertificateOperation('颁发证书失败', {
          studentId: form.value.studentId,
          error: error.message
        }, 'error', error.message);
        
        ElMessage.error('创建证书失败: ' + (error.message || '未知错误'));
      } finally {
        submitting.value = false;
      }
    };

    const handleRevoke = async (certificateId) => {
      try {
        await ElMessageBox.confirm('确定要撤销此证书吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        try {
          const response = await store.dispatch('revokeCertificate', certificateId);
          
          // 无论API结果如何，强制更新前端UI状态
          const cert = filteredCertificates.value.find(c => c.certificateId === certificateId);
          if (cert) {
            cert.isValid = false;
            console.log('已强制更新本地证书状态');
          }
          
          ElMessage.success(response?.message || '证书已撤销');

          // 刷新证书列表
          setTimeout(() => {
            handleRefresh();
          }, 1000);

          // 添加日志记录
          LogService.logCertificateOperation(`撤销证书 ID:${certificateId}`, {
            certificateId
          });
        } catch (error) {
          console.error('撤销操作失败:', error);
          
          // 即使API失败，也更新本地状态
          const cert = store.state.certificates.find(c => c.certificateId === certificateId);
          if (cert) {
            cert.isValid = false;
            console.log('尽管API失败，仍然将本地证书状态标记为无效');
          }
          
          ElMessage.error('撤销证书失败，但已在本地标记为无效');
          
          // 尝试更新本地状态并刷新
          handleRefresh();
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('撤销证书失败：' + error.message)
        }
      }
    }

    const fetchCertificates = async () => {
      try {
        refreshing.value = true;
        loading.value = true; // 设置加载状态
        await store.dispatch('fetchCertificates', { 
          studentId: studentIdFilter.value || null 
        });
      } catch (error) {
        console.error('获取证书列表失败:', error);
        ElMessage.error('获取证书列表失败: ' + (error.message || '未知错误'));
      } finally {
        refreshing.value = false;
        loading.value = false; // 完成后重置加载状态
      }
    };

    const handleRefresh = async () => {
      try {
        refreshing.value = true;
        await fetchCertificates();
        ElMessage.success('证书列表已刷新');
      } catch (error) {
        console.error('刷新证书列表失败:', error);
      } finally {
        refreshing.value = false;
      }
    };

    const handleBack = () => {
      router.push({ name: 'Students' })
    }

    // 为每个证书直接使用原始学生ID
    const generateUniqueStudentId = (certificateId) => {
      // 获取对应证书的学生ID
      const certificate = store.state.certificates.find(cert => cert.certificateId === certificateId);
      if (certificate && certificate.studentId) {
        return certificate.studentId; // 直接返回原始学生ID
      }
      return "未知";
    }

    const copyToClipboard = (text) => {
      navigator.clipboard.writeText(text).then(() => {
        ElMessage.success('已复制到剪贴板');
      }).catch(err => {
        console.error('复制失败:', err);
        ElMessage.error('复制失败');
      });
    }

    const viewCertificateDetails = (certificate) => {
      console.log('查看证书详情:', certificate);
      
      // 使用确认框而不是警告框，以便有两个按钮
      ElMessageBox.confirm(
        `<div class="cert-details">
          <div class="cert-details-header">
            <div class="cert-icon"><i class="el-icon-document"></i></div>
            <h3>证书信息</h3>
          </div>
          <div class="cert-details-content">
            <div class="cert-detail-item">
              <span class="detail-label">证书ID:</span>
              <span class="detail-value">${certificate.certificateId}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">学生ID:</span>
              <span class="detail-value">${certificate.studentId}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">证书类型:</span>
              <span class="detail-value">${removeQuotes(certificate.certificateType) || '未指定'}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">证书编号:</span>
              <span class="detail-value">${removeQuotes(certificate.certificateNumber) || '未指定'}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">颁发日期:</span>
              <span class="detail-value">${formatDate(certificate.timestamp)}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">颁发机构:</span>
              <span class="detail-value">${removeQuotes(certificate.institution) || '未指定'}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">区块信息:</span>
              <span class="detail-value">${certificate.blockNumber ? '区块 #' + certificate.blockNumber : '未知'}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">证书哈希:</span>
              <span class="detail-value hash-value">${certificate.certificateHash || certificate.hash || '未知'}</span>
            </div>
            <div class="cert-detail-item">
              <span class="detail-label">状态:</span>
              <span class="detail-value status-value ${certificate.isValid ? 'valid' : 'invalid'}">${certificate.isValid ? '有效' : '已撤销'}</span>
            </div>
          </div>
        </div>`,
        '证书详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '验证证书',
          cancelButtonText: '关闭',
          type: 'info',
          showClose: true,
          customClass: 'custom-message-box',
          callback: (action) => {
            if (action === 'confirm') {
              // 点击验证按钮
              verifyCertificate(certificate);
            } else {
              console.log('关闭证书详情对话框');
            }
          }
        }
      );
    };

    const verifyCertificate = async (certificate) => {
      try {
        console.log('开始验证证书:', certificate);
        
        // 确保有证书ID或哈希
        if (!certificate.certificateId && !certificate.hash && !certificate.certificateHash) {
          ElMessage.error('缺少证书ID或哈希值，无法验证');
          // 记录验证失败日志
          LogService.logCertificateOperation('证书验证失败-缺少ID或哈希', {
            certificateId: certificate.certificateId || '未提供',
            hash: certificate.hash || certificate.certificateHash || '未提供'
          }, 'error', '缺少证书ID或哈希值');
          return;
        }
        
        // 记录开始验证操作
        LogService.logCertificateOperation('开始验证证书', {
          certificateId: certificate.certificateId || '未提供',
          hash: certificate.hash || certificate.certificateHash || '未提供'
        });
        
        // 在当前数据中验证证书状态
        const currentCert = store.state.certificates.find(c => 
          c.certificateId === certificate.certificateId
        );
        
        if (currentCert && currentCert.isValid === false) {
          ElMessage.error('证书已被撤销，当前状态为无效');
          // 记录验证失败日志
          LogService.logCertificateOperation('证书验证失败-已撤销', {
            certificateId: certificate.certificateId,
            status: '已撤销'
          }, 'error', '证书已被撤销');
          return;
        }
        
        // 先刷新证书列表，确保有最新状态
        const loadingMsg = ElMessage({
          message: '正在获取最新证书状态...',
          type: 'info',
          duration: 0
        });
        
        try {
          // 强制刷新证书列表
          await store.dispatch('fetchCertificates', { forceRefresh: true });
          
          // 获取刷新后的证书
          const refreshedCert = store.state.certificates.find(c => 
            c.certificateId === certificate.certificateId
          );
          
          // 关闭第一个加载消息
          loadingMsg.close();
          
          if (refreshedCert) {
            console.log('刷新后的证书状态:', refreshedCert);
            
            // 使用刷新后的证书状态
            if (refreshedCert.isValid === false) {
              ElMessage.error('证书已被撤销，当前状态为无效');
              // 记录验证失败日志
              LogService.logCertificateOperation('证书验证失败-最新状态为撤销', {
                certificateId: certificate.certificateId,
                status: '已撤销'
              }, 'error', '证书已被撤销');
              return;
            }
          }
          
          // 执行标准验证
          const verifyMsg = ElMessage({
            message: '正在验证证书...',
            type: 'info',
            duration: 0
          });
          
          const result = await store.dispatch('verifyCertificate', {
            certificateId: certificate.certificateId,
            hash: certificate.hash || certificate.certificateHash
          });
          
          verifyMsg.close();
          
          if (result) {
            ElMessage.success('证书验证通过，证书有效');
            // 记录验证成功日志
            LogService.logCertificateOperation('证书验证成功', {
              certificateId: certificate.certificateId,
              hash: certificate.hash || certificate.certificateHash || '未提供',
              status: '有效'
            });
          } else {
            // 验证失败，更新本地状态
            const cert = store.state.certificates.find(c => 
              c.certificateId === certificate.certificateId
            );
            
            if (cert) {
              cert.isValid = false;
              console.log('验证失败，更新本地证书状态为无效');
            }
            
            ElMessage.error('证书验证失败，证书无效或已被撤销');
            // 记录验证失败日志
            LogService.logCertificateOperation('证书验证失败-链上状态无效', {
              certificateId: certificate.certificateId,
              hash: certificate.hash || certificate.certificateHash || '未提供',
              status: '无效'
            }, 'error', '证书无效或已被撤销');
          }
        } catch (error) {
          loadingMsg.close();
          throw error;
        }
      } catch (error) {
        console.error('验证证书失败:', error);
        ElMessage.error('验证证书失败: ' + (error.message || '未知错误'));
        
        // 记录验证错误日志
        LogService.logCertificateOperation('证书验证异常', {
          certificateId: certificate?.certificateId || '未提供',
          hash: certificate?.hash || certificate?.certificateHash || '未提供'
        }, 'error', error.message || '未知错误');
      }
    };

    const openUpdateDialog = (certificate) => {
      // 复制证书信息到更新表单，并且去除所有引号
      updateForm.value = {
        certificateId: certificate.certificateId,
        studentId: certificate.studentId,
        certificateType: removeQuotes(certificate.certificateType) || '',
        certificateNumber: removeQuotes(certificate.certificateNumber) || '',
        issueDate: certificate.issueDate || 
                  formatDate(certificate.timestamp).replace(/\//g, '-') || 
                  new Date().toISOString().split('T')[0],
        institution: removeQuotes(certificate.institution) || '',
        isValid: certificate.isValid !== false // 确保是布尔值
      }
      updateDialogVisible.value = true
    }

    const handleUpdate = async () => {
      try {
        console.log('准备更新证书:', updateForm.value)
        
        // 确保表单数据完整
        if (!updateForm.value.certificateType || !updateForm.value.certificateNumber || 
            !updateForm.value.issueDate || !updateForm.value.institution) {
          ElMessage.warning('请填写完整的证书信息')
          return
        }

        const loadingMsg = ElMessage({
          message: '正在更新证书...',
          type: 'info',
          duration: 0
        })
        
        try {
          // 确保提交数据中不包含引号
          const submitData = {
            studentId: updateForm.value.studentId,
            certificateType: removeQuotes(updateForm.value.certificateType),
            certificateNumber: removeQuotes(updateForm.value.certificateNumber),
            issueDate: updateForm.value.issueDate,
            institution: removeQuotes(updateForm.value.institution),
            isValid: updateForm.value.isValid
          };
          
          // 调用store的updateCertificate方法
          const response = await store.dispatch('updateCertificate', {
            certificateId: updateForm.value.certificateId,
            certificateData: submitData
          })
          
          loadingMsg.close()
          
          if (response?.code === 0 || response?.data) {
            ElMessage.success('更新证书成功')
            updateDialogVisible.value = false
            
            // 刷新证书列表
            setTimeout(() => {
              handleRefresh()
            }, 1000)
          } else {
            throw new Error(response?.message || '更新失败')
          }
        } catch (error) {
          loadingMsg.close()
          throw error
        }
      } catch (error) {
        console.error('更新证书失败:', error)
        ElMessage.error('更新证书失败: ' + error.message)
      }
    }

    // 当前活动标签
    const activeTab = ref('browse')
    
    // 设置活动标签
    const setActiveTab = (tab) => {
      activeTab.value = tab
    }

    // 处理撤销证书对话框
    const handleRevokeDialog = () => {
      ElMessageBox.confirm(
        '您确定要撤销选中的证书吗？此操作不可逆。',
        '撤销确认',
        {
          confirmButtonText: '确认撤销',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage({
          type: 'success',
          message: '证书已撤销'
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消撤销'
        })
      })
    }

    // 添加表单重置函数
    const resetForm = () => {
      form.value.studentId = studentIdFilter.value || '';
      form.value.certificateType = '';
      form.value.certificateNumber = '';
      form.value.issueDate = new Date().toISOString().split('T')[0];
      form.value.institution = 'HBFU';
    };

    // 导出证书数据
    const exportCertificates = () => {
      if (filteredCertificates.value.length === 0) {
        ElMessage.warning('暂无证书数据可导出');
        return;
      }

      // 创建一个对话框让用户选择导出格式
      ElMessageBox.confirm(
        '<div style="text-align:center">请选择导出格式</div>',
        '导出证书数据',
        {
          confirmButtonText: 'CSV格式',
          cancelButtonText: 'JSON格式',
          distinguishCancelAndClose: true,
          closeOnClickModal: false,
          dangerouslyUseHTMLString: true,
          center: true,
          customClass: 'export-dialog'
        }
      )
        .then(() => {
          // 用户选择了CSV格式
          exportAsCSV();
          // 记录日志
          LogService.logCertificateOperation('导出证书数据', { format: 'CSV', count: filteredCertificates.value.length });
        })
        .catch((action) => {
          if (action === 'cancel') {
            // 用户选择了JSON格式
            exportAsJSON();
            // 记录日志
            LogService.logCertificateOperation('导出证书数据', { format: 'JSON', count: filteredCertificates.value.length });
          }
        });
    }

    // 导出为CSV格式
    const exportAsCSV = () => {
      // CSV表头
      const headers = ['证书ID', '学生ID', '学生姓名', '颁发日期', '状态', '证书Hash'];
      // 组合CSV内容
      let csvContent = headers.join(',') + '\r\n';
      
      filteredCertificates.value.forEach(cert => {
        const row = [
          cert.certificateId,
          cert.studentId,
          `"${cert.studentName || ''}"`, // 添加引号以处理可能包含逗号的名称
          formatDate(cert.timestamp),
          cert.isValid ? '有效' : '已撤销',
          cert.hash
        ];
        csvContent += row.join(',') + '\r\n';
      });
      
      // 创建Blob对象
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      saveFile(blob, `证书数据_${new Date().toISOString().split('T')[0]}.csv`);
      
      ElMessage.success('证书数据已成功导出为CSV格式');
    }

    // 导出为JSON格式
    const exportAsJSON = () => {
      // 创建一个仅包含需要的数据的对象
      const exportData = filteredCertificates.value.map(cert => ({
        certificateId: cert.certificateId,
        studentId: cert.studentId,
        studentName: cert.studentName || '',
        issueDate: formatDate(cert.timestamp),
        status: cert.isValid ? '有效' : '已撤销',
        hash: cert.hash
      }));
      
      // 创建Blob对象
      const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
      saveFile(blob, `证书数据_${new Date().toISOString().split('T')[0]}.json`);
      
      ElMessage.success('证书数据已成功导出为JSON格式');
    }

    // 保存文件的通用方法
    const saveFile = (blob, fileName) => {
      // 创建下载链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      
      // 添加到文档并触发点击
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }

    // 显示帮助信息
    const showHelp = () => {
      ElMessageBox.alert(
        `<div class="help-content">
          <h3>证书管理系统使用指南</h3>
          <p><strong>基本功能：</strong></p>
          <ul>
            <li><strong>颁发证书：</strong> 点击悬浮按钮中的"颁发证书"按钮，选择学生并填写证书信息</li>
            <li><strong>撤销证书：</strong> 在证书列表中点击"撤销"按钮，可以将证书状态变更为已撤销</li>
            <li><strong>导出数据：</strong> 点击悬浮按钮中的"导出数据"按钮，选择导出格式(CSV或JSON)后，系统将自动下载证书数据文件</li>
            <li><strong>刷新列表：</strong> 点击悬浮按钮中的"刷新列表"按钮，可以更新证书数据</li>
          </ul>
          <p><strong>数据导出说明：</strong></p>
          <ul>
            <li>CSV格式：适合在Excel等电子表格软件中打开查看</li>
            <li>JSON格式：适合开发人员或数据分析使用</li>
            <li>导出的数据包括：证书ID、学生ID、学生姓名、颁发日期、状态和证书Hash</li>
          </ul>
          <p><strong>注意事项：</strong></p>
          <ul>
            <li>证书一旦颁发到区块链上，信息将不可更改</li>
            <li>撤销证书只是改变证书状态，并不会删除证书数据</li>
            <li>所有操作都会被记录在系统日志中，方便后续追踪</li>
          </ul>
        </div>`,
        '帮助信息',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '我知道了',
          customClass: 'help-dialog'
        }
      );
      
      // 记录日志
      LogService.logSystemOperation('查看证书管理帮助');
    }

    onMounted(() => {
      console.log('证书组件已挂载，开始获取数据...');
      loading.value = true; // 设置加载状态为true
      store.dispatch('fetchStudents')
      store.dispatch('fetchCertificates', { limit: 1000 })
        .then(() => {
          console.log('证书数据加载完成，当前证书列表:', store.state.certificates);
          loading.value = false; // 数据加载完成，设置为false
        })
        .catch(error => {
          console.error('加载证书数据时出错:', error);
          loading.value = false; // 发生错误时也设置为false
        });
      
      // 添加日志记录
      LogService.logCertificateOperation('访问证书管理页面');
    })

    return {
      dialogVisible,
      form,
      submitForm,
      handleRevoke,
      handleRefresh,
      filteredCertificates,
      students: computed(() => store.state.students),
      loading, // 将loading状态暴露给模板
      refreshing,
      formatDate,
      removeQuotes,
      studentIdFilter,
      handleBack,
      generateUniqueStudentId,
      copyToClipboard,
      viewCertificateDetails,
      verifyCertificate,
      updateDialogVisible,
      updateForm,
      openUpdateDialog,
      handleUpdate,
      handleRevokeDialog,
      activeTab,
      setActiveTab,
      submitting,
      resetForm,
      fetchCertificates,
      exportCertificates,
      exportAsCSV,
      exportAsJSON,
      saveFile,
      showHelp,
      searchQuery,
      filterInvalidDates,
      handleSearch,
      handleFilterChange,
      isDataEmpty
    }
  }
}
</script>

<style scoped>
.certificates-page {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
  position: relative;
  overflow: hidden;
}

/* 增强粒子背景效果 */
.particles-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  overflow: hidden;
  pointer-events: none;
}

.particle {
  position: absolute;
  width: var(--size);
  height: var(--size);
  background: radial-gradient(circle, rgba(97, 73, 205, 0.8) 0%, rgba(97, 73, 205, 0) 70%);
  border-radius: 50%;
  top: calc(var(--position) - 50px);
  left: calc(var(--position) - 50px);
  animation: float var(--duration) ease-in-out var(--delay) infinite;
  opacity: 0.4;
  filter: blur(8px);
}

.particle:nth-child(even) {
  background: radial-gradient(circle, rgba(52, 179, 241, 0.8) 0%, rgba(52, 179, 241, 0) 70%);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) translateX(0) scale(1);
    opacity: 0.2;
  }
  25% {
    transform: translateY(-100px) translateX(50px) scale(1.2);
    opacity: 0.4;
  }
  50% {
    transform: translateY(-30px) translateX(100px) scale(0.8);
    opacity: 0.6;
  }
  75% {
    transform: translateY(-70px) translateX(30px) scale(1.1);
    opacity: 0.4;
  }
}

/* 增强页面标题样式 */
.page-title-section {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
  padding: 20px 0;
}

.magical-title {
  font-size: 36px;
  font-weight: 700;
  color: transparent;
  background: linear-gradient(45deg, #34b3f1, #6149cd, #6149cd, #34b3f1);
  background-size: 300% 300%;
  background-clip: text;
  -webkit-background-clip: text;
  animation: gradientText 6s ease infinite;
  position: relative;
  display: inline-block;
  margin: 0;
  letter-spacing: 2px;
  text-shadow: 0 10px 20px rgba(97, 73, 205, 0.15);
}

@keyframes gradientText {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.magical-underline {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  width: 220px;
  height: 3px;
  background: linear-gradient(90deg, rgba(97,73,205,0) 0%, rgba(97,73,205,1) 50%, rgba(97,73,205,0) 100%);
  box-shadow: 0 4px 8px rgba(97, 73, 205, 0.3);
}

/* 增强卡片样式 */
.main-card {
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  overflow: hidden;
  border: none;
  position: relative;
  transition: all 0.5s;
  margin-bottom: 30px;
}

.main-card:hover {
  box-shadow: 0 15px 50px rgba(52, 179, 241, 0.25);
  transform: translateY(-5px);
}

/* 增强表格样式 */
.certificate-table {
  width: 100%;
  margin: 0 auto;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.07);
  transition: all 0.3s;
}

:deep(.el-table__row) {
  transition: all 0.3s;
  height: 60px;
}

:deep(.el-table__row:hover) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.07);
  z-index: 1;
  position: relative;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: rgba(52, 179, 241, 0.05);
}

/* 增强状态标签样式 */
:deep(.el-tag.el-tag--success) {
  background: linear-gradient(145deg, #67c23a, #85ce61);
  border: none;
  color: white;
  padding: 2px 10px;
  font-weight: 500;
  box-shadow: 0 3px 8px rgba(103, 194, 58, 0.2);
}

:deep(.el-tag.el-tag--danger) {
  background: linear-gradient(145deg, #f56c6c, #ff9b9b);
  border: none;
  color: white;
  padding: 2px 10px;
  font-weight: 500;
  box-shadow: 0 3px 8px rgba(245, 108, 108, 0.2);
}

/* 增强操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

:deep(.el-button--info) {
  background: linear-gradient(to right, #909399, #c0c4cc);
  border: none;
  color: white;
  transition: all 0.3s;
}

:deep(.el-button--info:hover) {
  background: linear-gradient(to right, #c0c4cc, #909399);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(144, 147, 153, 0.3);
}

:deep(.el-button--danger) {
  background: linear-gradient(to right, #f56c6c, #ff9b9b);
  border: none;
  color: white;
  transition: all 0.3s;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(to right, #ff9b9b, #f56c6c);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(245, 108, 108, 0.3);
}

:deep(.el-button--primary) {
  background: linear-gradient(to right, #409eff, #79bbff);
  border: none;
  color: white;
  transition: all 0.3s;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(to right, #79bbff, #409eff);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
}

/* 证书ID单元格样式增强 */
.student-id-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.id-code {
  font-family: 'Consolas', monospace;
  background-color: rgba(52, 179, 241, 0.1);
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid rgba(52, 179, 241, 0.2);
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
  display: inline-block;
  max-width: 240px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.id-code:hover {
  background-color: rgba(52, 179, 241, 0.15);
  transform: translateY(-1px);
}

/* 对话框美化 */
.fancy-dialog {
  border-radius: 16px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.25);
}

.dialog-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(ellipse at top left, rgba(97,73,205,0.1) 0%, rgba(97,73,205,0) 70%),
              radial-gradient(ellipse at bottom right, rgba(52,179,241,0.1) 0%, rgba(52,179,241,0) 70%);
  z-index: -1;
  pointer-events: none;
}

/* 顶部状态提示 */
.status-notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 新增：添加证书流程指引 */
.cert-process-guide {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(52, 179, 241, 0.05);
  border-radius: 12px;
  position: relative;
}

.process-step {
  text-align: center;
  position: relative;
  flex: 1;
}

.step-number {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #34b3f1, #6149cd);
  color: white;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  box-shadow: 0 4px 10px rgba(97, 73, 205, 0.3);
}

.step-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.step-desc {
  font-size: 13px;
  color: #606266;
}

.process-connector {
  position: absolute;
  top: 18px;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(to right, #34b3f1, #6149cd);
  z-index: -1;
}

/* 更多样式 - 保留原有样式... */
.glow-effect {
  position: absolute;
  top: -100px;
  left: -100px;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(97,73,205,0.3) 0%, rgba(97,73,205,0) 70%);
  border-radius: 50%;
  filter: blur(20px);
  animation: moveGlow 10s infinite alternate ease-in-out;
  z-index: 0;
  pointer-events: none;
}

@keyframes moveGlow {
  0% {
    top: -100px;
    left: -100px;
  }
  25% {
    top: 30%;
    left: 80%;
  }
  50% {
    top: 70%;
    left: 20%;
  }
  75% {
    top: 10%;
    left: 50%;
  }
  100% {
    top: 50%;
    left: 80%;
  }
}

/* 图标容器与动画 */
.icon-container {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #34b3f1, #6149cd);
  border-radius: 50%;
  margin-right: 10px;
  position: relative;
  overflow: hidden;
}

.icon-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(255,255,255,0.8), transparent);
  transform: rotate(45deg);
  animation: shimmer 3s infinite;
  pointer-events: none;
}

@keyframes shimmer {
  0% { transform: translateX(-100%) rotate(45deg); }
  100% { transform: translateX(100%) rotate(45deg); }
}

.floating-icon {
  animation: floatingIcon 3s ease-in-out infinite;
  color: #909399;
  font-size: 36px;
  margin-bottom: 10px;
  display: block;
}

@keyframes floatingIcon {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

/* 按钮特效 */
.magical-btn {
  position: relative;
  overflow: hidden;
  z-index: 1;
  transition: all 0.3s;
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 500;
  letter-spacing: 0.5px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
}

.magical-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(97, 73, 205, 0.2);
  background: linear-gradient(to right, #6149cd, #34b3f1);
}

.magical-btn:focus,
.magical-btn:active {
  color: white;
  border: none;
}

.btn-bg-effect {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, #34b3f1, #6149cd, #6149cd, #34b3f1);
  background-size: 300% 300%;
  animation: gradientBg 3s ease infinite;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: -1;
}

.magical-btn:hover .btn-bg-effect {
  opacity: 0.2;
}

@keyframes gradientBg {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 表格容器样式 */
.table-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  width: 98%;
  margin: 0 auto;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 12px;
  padding: 2px 10px;
  font-weight: 500;
  font-size: 14px;
}

.filter-tag {
  margin-left: 10px;
  font-size: 13px;
  background-color: rgba(64, 158, 255, 0.1);
}

.action-buttons .el-button {
  margin: 0;
  border-radius: 20px;
  padding: 6px 15px;
}

/* 表单对话框样式增强 */
.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(97, 73, 205, 0.2);
  position: relative;
  overflow: hidden;
}

.form-header::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg, #34b3f1, #6149cd, #34b3f1);
  animation: shimmerBorder 3s infinite linear;
  background-size: 200% 100%;
}

@keyframes shimmerBorder {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.certificate-icon-container {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #34b3f1, #6149cd);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(97, 73, 205, 0.3);
}

.certificate-icon-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(255,255,255,0.8), transparent);
  transform: rotate(45deg);
  animation: shimmer 3s infinite;
}

.certificate-icon-container.update-icon {
  background: linear-gradient(135deg, #f19b34, #cd6149);
  box-shadow: 0 5px 15px rgba(205, 97, 73, 0.3);
}

.floating-dialog-icon {
  color: white;
  font-size: 24px;
  animation: pulseIcon 3s ease-in-out infinite;
}

.form-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.styled-form {
  padding: 0 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #4a5568;
  padding-bottom: 5px;
  font-size: 15px;
}

.styled-input,
.styled-select,
.styled-date-picker {
  width: 100% !important;
  display: block !important;
}

:deep(.el-input__inner),
:deep(.el-select .el-input__inner),
:deep(.el-date-editor.el-input__inner) {
  border-radius: 8px;
  padding: 12px 15px 12px 40px;
  height: 45px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.9);
  box-sizing: border-box;
}

:deep(.el-input__inner:focus),
:deep(.el-select .el-input__inner:focus),
:deep(.el-date-editor.el-input__inner:focus) {
  border-color: #6149cd;
  box-shadow: 0 0 0 2px rgba(97, 73, 205, 0.2);
}

:deep(.el-input__prefix) {
  left: 10px;
  height: 100%;
  display: flex;
  align-items: center;
  pointer-events: none;
}

:deep(.el-input__prefix-inner i) {
  font-size: 18px;
  color: #6149cd;
}

:deep(.el-date-editor .el-input__prefix) {
  left: 10px;
}

:deep(.el-date-editor.el-input) {
  width: 100% !important;
}

:deep(.el-date-editor .el-input__inner) {
  padding-left: 40px !important;
}

.form-icon {
  color: #6149cd;
  font-size: 16px;
  margin-right: 5px;
}

/* 修复日期选择器样式 */
:deep(.el-date-editor.el-input),
:deep(.el-date-editor.el-input__inner) {
  width: 100% !important;
}

/* 修复下拉框样式 */
:deep(.el-select) {
  width: 100% !important;
  display: block !important;
}

:deep(.el-select .el-input) {
  width: 100% !important;
}

:deep(.el-select .el-input__suffix) {
  right: 5px;
}

/* 表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__content) {
  display: block !important;
  line-height: normal;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  margin-left: 2px;
}

.floating-dots {
  display: flex;
  gap: 5px;
  margin-left: 10px;
}

.floating-dots span {
  width: 6px;
  height: 6px;
  background-color: #6149cd;
  border-radius: 50%;
  display: inline-block;
}

.floating-dots span:nth-child(1) {
  animation: dot-float 1.5s infinite ease-in-out;
}

.floating-dots span:nth-child(2) {
  animation: dot-float 1.5s infinite ease-in-out 0.3s;
}

.floating-dots span:nth-child(3) {
  animation: dot-float 1.5s infinite ease-in-out 0.6s;
}

@keyframes dot-float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

.magic-effect-container {
  position: relative;
  width: 20px;
  height: 20px;
}

.magic-sparkle {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(circle, #6149cd 0%, transparent 60%);
  border-radius: 50%;
  animation: sparkle 2s infinite;
}

@keyframes sparkle {
  0%, 100% { transform: scale(0.5); opacity: 0.2; }
  50% { transform: scale(1.2); opacity: 0.8; }
}

.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-description {
  color: #909399;
  margin-left: auto;
  font-size: 12px;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: rgba(97, 73, 205, 0.1);
  color: #6149cd;
  font-weight: 600;
}

:deep(.el-select-dropdown__item i) {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.switch-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.switch-status {
  font-size: 14px;
  padding: 2px 12px;
  border-radius: 20px;
  transition: all 0.3s;
}

.switch-status.valid {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.switch-status.invalid {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

:deep(.el-switch__core) {
  border-radius: 12px;
  width: 50px;
  height: 24px;
}

:deep(.el-switch__label) {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.form-notice {
  margin-top: 15px;
  padding: 10px 15px;
  background-color: rgba(103, 194, 58, 0.1);
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-notice.warning {
  background-color: rgba(230, 162, 60, 0.1);
}

.notice-icon {
  font-size: 18px;
  color: #67c23a;
}

.form-notice.warning .notice-icon {
  color: #e6a23c;
}

.form-notice span {
  font-size: 13px;
  color: #606266;
}

.submit-btn {
  padding: 10px 25px;
  height: auto;
  font-size: 15px;
  background: linear-gradient(to right, #34b3f1, #6149cd);
  border: none;
}

.submit-btn:hover {
  background: linear-gradient(to right, #6149cd, #34b3f1);
}

.cancel-btn {
  padding: 10px 25px;
  height: auto;
  font-size: 15px;
  background: transparent;
  border: 1px solid #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background: #f5f7fa;
  color: #409eff;
  border-color: #c6e2ff;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  width: 100%;
}

/* 日期选择器容器 */
.date-picker-wrapper {
  width: 100%;
}

/* 修复日期选择器样式 */
:deep(.el-date-editor.el-input) {
  width: 100% !important;
}

:deep(.el-date-editor .el-input__inner) {
  padding-left: 40px !important;
}

/* 图标位置修复 */
:deep(.el-input__icon),
:deep(.el-date-editor .el-input__icon) {
  line-height: normal;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确保所有输入框和选择器宽度一致 */
.styled-input,
.styled-select,
.styled-date-picker {
  width: 100% !important;
  display: block !important;
}

/* 表单项样式修复 */
:deep(.el-form-item__content) {
  display: block !important;
  line-height: normal;
}

/* 确保所有选择器弹出内容正常 */
:deep(.el-select-dropdown) {
  width: auto !important;
  min-width: 200px !important;
}

/* 添加新的标签样式 */
.certificate-tabs-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
  padding: 0 10px;
  border-bottom: 1px solid #ebeef5;
}

.certificate-tabs {
  display: flex;
  align-items: center;
}

.tab {
  padding: 12px 20px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
  transition: all 0.3s;
  margin-right: 15px;
  border-bottom: 2px solid transparent;
}

.tab i {
  margin-right: 6px;
  font-size: 16px;
}

.tab:hover {
  color: #409EFF;
}

.tab.active {
  color: #409EFF;
  font-weight: 500;
  border-bottom: 2px solid #409EFF;
}

.tab.active::after {
  display: none;
}

.tab-actions {
  display: flex;
  gap: 10px;
}

/* 帮助对话框和导出对话框样式 */
:deep(.help-dialog) .el-message-box__wrapper,
:deep(.export-dialog) .el-message-box__wrapper {
  backdrop-filter: blur(10px);
}

:deep(.help-dialog) .el-message-box,
:deep(.export-dialog) .el-message-box {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(100, 100, 255, 0.2);
  background: linear-gradient(145deg, #ffffff, #f8f9fc);
  max-width: 500px;
}

:deep(.help-dialog) .el-message-box__header,
:deep(.export-dialog) .el-message-box__header {
  padding: 15px 20px;
  background: linear-gradient(45deg, #6149cd, #34b3f1);
  border-radius: 12px 12px 0 0;
}

:deep(.help-dialog) .el-message-box__title,
:deep(.export-dialog) .el-message-box__title {
  color: white;
  font-weight: bold;
}

:deep(.help-dialog) .el-message-box__content,
:deep(.export-dialog) .el-message-box__content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.help-dialog) .el-button,
:deep(.export-dialog) .el-button {
  padding: 8px 24px;
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.help-dialog) .el-button:hover,
:deep(.export-dialog) .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.help-content {
  line-height: 1.6;
}

.help-content h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #6149cd;
  border-bottom: 2px solid #34b3f1;
  padding-bottom: 8px;
}

.help-content p {
  margin: 12px 0;
}

.help-content ul {
  padding-left: 20px;
  margin: 10px 0;
}

.help-content li {
  margin-bottom: 8px;
}

.help-content strong {
  color: #6149cd;
}

.empty-text {
  text-align: center;
  margin-top: 20px;
  color: #909399;
}

.magical-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(97,73,205,0.3) 0%, rgba(97,73,205,0) 70%);
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 添加搜索和过滤容器样式 */
.search-filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(5px);
  transition: all 0.3s;
}

.search-filter-container:hover {
  box-shadow: 0 6px 16px rgba(97, 73, 205, 0.1);
  transform: translateY(-2px);
}

.search-input {
  flex-grow: 1;
  margin-right: 15px;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  padding-left: 40px;
  height: 42px;
  border: 1px solid #e0e3e9;
  transition: all 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #6149cd;
  box-shadow: 0 0 0 2px rgba(97, 73, 205, 0.1);
}

:deep(.el-input__prefix) {
  left: 15px;
}

:deep(.el-input__prefix i) {
  font-size: 16px;
  color: #6149cd;
}

:deep(.el-switch__label) {
  color: #606266;
}

:deep(.el-switch__label.is-active) {
  color: #6149cd;
}

:deep(.el-switch__label--right) {
  margin-left: 10px;
}

:deep(.el-switch__label--left) {
  margin-right: 10px;
}

.floating-icon {
  animation: floatingIcon 3s ease-in-out infinite;
  color: #909399;
  font-size: 36px;
  margin-bottom: 10px;
  display: block;
}

@keyframes floatingIcon {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}
</style> 